package com.example.resourceofDengJL.service;

import com.example.resourceofDengJL.bean.Student;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/students")
@CrossOrigin(origins = "*")  // 允许前端跨域访问
public class StudentController {
    private List<Student> students = new ArrayList<>();

    //添加学生
    @PostMapping
    public ResponseEntity<String> addStudent(@RequestBody Student student) {
        // 检查学号是否已存在
        boolean exists = students.stream()
                .anyMatch(s -> s.getId().equals(student.getId()));

        if (exists) {
            return ResponseEntity.status(HttpStatus.CONFLICT)
                    .body("学号 " + student.getId() + " 已存在");
        }

        students.add(student);
        return ResponseEntity.ok("学生添加成功");
    }


    //获取学生
    @GetMapping
    public List<Student> getStudents() {
        return students;
    }



    // 获取指定学号学生
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable String id) {
        return students.stream()
                .filter(s -> s.getId().equals(id))
                .findFirst()
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 更新学生信息
    @PutMapping("/{id}")
    public ResponseEntity<String> updateStudent(
            @PathVariable String id,
            @RequestBody Student updatedStudent) {

        Optional<Student> existing = students.stream()
                .filter(s -> s.getId().equals(id))
                .findFirst();

        if (!existing.isPresent()) {
            return ResponseEntity.notFound().build();
        }

        Student student = existing.get();
        student.setName(updatedStudent.getName());
        student.setBirthDate(updatedStudent.getBirthDate());

        return ResponseEntity.ok("学生信息更新成功");
    }

    // 删除学生
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteStudent(@PathVariable String id) {
        boolean removed = students.removeIf(s -> s.getId().equals(id));
        return removed ?
                ResponseEntity.ok("学生删除成功") :
                ResponseEntity.notFound().build();
    }

}
